// 政采云财务对账服务
'use strict';

const Service = require('egg').Service;
const { Op } = require('sequelize');

class FinanceService extends Service {
  /**
   * 执行每日对账（符合政采云财务规范GB/T 24589）
   * @param {String} provinceCode 省份编码
   */
  async dailyReconciliation(provinceCode) {
    const { ctx } = this;
    
    // 获取当日订单数据
    const orders = await ctx.model.Order.findAll({
      where: {
        province_code: provinceCode,
        createdAt: {
          [Op.between]: [
            ctx.helper.getDayStart(),
            ctx.helper.getDayEnd()
          ]
        }
      },
      transaction: ctx.transaction
    });

    // 调用政采云支付对账API
    const apiResult = await ctx.curl(`${ctx.app.config.zcy.apiEndpoint}/payment/reconciliation`, {
      method: 'POST',
      dataType: 'json',
      data: {
        provinceCode,
        date: ctx.helper.formatDate(new Date())
      }
    });

    // 差异检测算法
    const discrepancies = this._findDiscrepancies(orders, apiResult.data.items);
    
    // 生成符合财委格式的差异报告
    const report = await ctx.service.report.generate({
      template: 'finance-discrepancy',
      data: discrepancies
    });

    // 写入区块链存证（符合政采云审计要求）
    await ctx.service.blockchain.record({
      action: 'FINANCE_RECONCILIATION',
      hash: ctx.helper.fileHash(report)
    });

    return report;
  }

  // 私有方法：订单与支付记录比对
  _findDiscrepancies(localOrders, remoteRecords) {
    // 实现基于金额和订单号的交叉验证算法
  }
}

module.exports = FinanceService;